package com.yanxu.lock.fairandunfair;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025/3/16-2025
 * @Description: 演示非公平锁现象
 */
public class NotFairLock {
    public static void main(String[] args) {
        PrintQueue2 printQueue2 = new PrintQueue2();
        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+" 开始打印!!!");
                    printQueue2.printJob("");
                    System.out.println(Thread.currentThread().getName()+" 打印完毕!!!");
                }
            },"线程"+i).start();
        }
    }
}

class PrintQueue2 {
    //定义一个非公平锁
    Lock lock = new ReentrantLock(false);

    public void printJob(Object document) {
        //第一次打印
        lock.lock();
        try {
            int duration = new Random().nextInt(10) + 1;
            System.out.println(Thread.currentThread().getName() + "第一次，正在打印，需要" + duration + " 秒时间!!!");
            Thread.sleep(duration * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        //第二次打印
        lock.lock();
        try {
            int duration = new Random().nextInt(10) + 1;
            System.out.println(Thread.currentThread().getName() + "第二次，正在打印，需要" + duration + " 秒时间!!!");
            Thread.sleep(duration * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}